<?php

class Model
{
    # setup singleton
    protected static $_database;

    # reference to database connection instance
    protected $_db;

    # current table associate with model
    protected $_table;

    public function __construct($table = null)
    {
        if (!self::$_database) {
            self::$_database = new Database();
        }
        $this->_db =& self::$_database;

        # table được nhận biết qua tên model
        if ($table) {
            $this->_table = $table;
        } else {
            $this->_table = strtolower(get_class($this));
        }
    }

    public function selectAll()
    {
        return $this->_db->select($this->_table);
    }

    public function select($where = null, $bind = null,
        $fields = '*', $limit = null, $count = 10) {
        return $this->_db->select($this->_table, $where, $bind,
            $fields, $limit, $count);
    }

    public function update($info, $where, $bind = null)
    {
        return $this->_db->update($this->_table, $info, $where, $bind);
    }

    public function checkPassword($id, $pw)
    {
        return count($this->select('cb_id = :id AND cb_matkhau = :pw',
                array('id' => $id, 'pw' => generatePwd($pw))));
    }

    public function insert($info)
    {
        return $this->_db->insert($this->_table, $info);
    }

    public function delete($where, $bind = array())
    {
        $this->_db->delete($this->_table, $where, $bind);
    }

    public function __destruct()
    {
        $this->_db->disconnect();
    }
}